package com.mbcn.system.commonUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.mbcn.dao.MemberDAO;
import com.mbcn.dao.impl.MemberDAOImpl;
import com.mbcn.model.Member;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

//*****************************************************************************
//* ALL RIGHTS RESERVED. COPYRIGHT (C) 2013 ソリマチ株式会社              			      *
//*****************************************************************************
//* File Name    : Util       		                 						  *
//* Function     : Util Common            									  *
//* System Name  :                                 							  *
//* Create       : VanTrung 2013/06/18                                        *
//* Update       :                                                            *
//* Comment      :                                                            *
//*****************************************************************************
public class Util {

	/**
	 * Check string is empty
	 * 
	 * @param str
	 * @author vantrung
	 * @since 2013/07/22
	 * @return
	 */

	public static boolean isEmpty(String str) {
		return str == null || str.equals("");
	}

	/**
	 * Empty string
	 * 
	 * @param str
	 * @author vantrung
	 * @since 2013/07/22
	 * @return str
	 */
	public static String emptyString(String str) {
		if (str == null) {
			str = "";
		}
		str.replace(str, "");
		return str;
	}

	/**
	 * Get MD5
	 * 
	 * @param input
	 * @return
	 * @author VanTrung
	 * @since 2013/05/17
	 */
	public static String getMD5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(input.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			String hashtext = number.toString(16);
			// Now we need to zero pad it if you actually want the full 32
			// chars.
			while (hashtext.length() < 32) {
				hashtext = "0" + hashtext;
			}
			return hashtext;
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Get current time stamp
	 * 
	 * @return
	 * @author VanTrung
	 * @since 2013/05/17
	 */
	public static Timestamp getCurrentTimestamp() {
		// Create a java calendar instance
		Calendar calendar = Calendar.getInstance();
		// A java current time (now) instance
		return new Timestamp(calendar.getTimeInMillis());
	}

	 
	/**
	 * Get current string date
	 * 
	 * @param pattern
	 * @return
	 * @author VanTrung
	 * @since 2013/05/17
	 */
	public static String getCurrentStringDate(String pattern) {

		// Get current date
		Calendar currentDate = Calendar.getInstance();
		SimpleDateFormat formatter = new SimpleDateFormat(pattern);

		return formatter.format(currentDate.getTime());
	}

	 

	/**
	 * Convert Date to String with format
	 * 
	 * @param date
	 * @param format
	 * @return
	 * @author VanTrung
	 * @since 2013/05/17
	 */
	public static String convertDateToString(Date date, String format) {
		if (date == null) {
			return null;
		}
		try {
			DateFormat formatter = new SimpleDateFormat(format);

			return formatter.format(date);

		} catch (Exception e) {
			System.out.println("Exception :" + e);
			return null;
		}
	}

	 

	 

	 
	 

	/**
	 * Check number
	 * 
	 * @param value
	 * @return
	 * @author VanTrung
	 * @since 2013/05/17
	 */
	public static boolean isNumeric(String value) {
		if (value == null) {
			return false;
		} else {
			return (value
					.matches("^[-+]?(?:\\b[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+\\b)(?:[eE][-+]?[0-9]+\\b)?$"));
		}
	}

 

	 

	/**
	 * Get time 15 minute
	 * 
	 * @param currentDate
	 * @param lastLoginDate
	 * @return
	 */
	public static int minutesDiff(Date currentDate, Date lastLoginDate) {
		if (currentDate == null || lastLoginDate == null)
			return 0;

		return (int) ((currentDate.getTime() / 60000) - (lastLoginDate
				.getTime() / 60000));
	}

	/**
	 * Encode ASE
	 * 
	 * @param input
	 * @return
	 */
	public static String encrypt(String input) {
		byte[] crypted = null;
		String key = "buinguyenphuckey";// Readkey.readkey();
		String encryptedValue = "";
		try {
			SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, skey);
			crypted = cipher.doFinal(input.getBytes());
			encryptedValue = new BASE64Encoder().encode(crypted);
			encryptedValue = URLEncoder.encode(encryptedValue, "UTF-8");
			System.out.println(encryptedValue);
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return encryptedValue;
	}

	/**
	 * DECODE ASE
	 * 
	 * @param input
	 * @return
	 */
	public static String decrypt(String input) {
		String key = "buinguyenphuckey";
		String decryptedValue = "";
		try {
			SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, skey);
			input = URLDecoder.decode(input, "UTF-8");
			@SuppressWarnings("restriction")
			byte[] decordedValue = new BASE64Decoder().decodeBuffer(input);
			byte[] decValue = cipher.doFinal(decordedValue);
			decryptedValue = new String(decValue);
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return decryptedValue;
	}

	/**
	 * Get pathName
	 * 
	 * @author vantrung
	 * @since 2013/08/01
	 * 
	 * @return path
	 */
	public static String getPathName() {
		String pathName = "";
		HttpServletRequest request = ServletActionContext.getRequest();
		pathName = request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + request.getContextPath();
		return pathName;
	}

	/**
	 * Get ip client
	 * 
	 * @author vantrung
	 * @since 2013/08/01
	 * @return
	 */
	public static String getIpClient() {
		String ipClient = "";
		HttpServletRequest request = ServletActionContext.getRequest();
		ipClient = request.getRemoteAddr();
		return ipClient;
	}

	/**
	 * @method formatNumber
	 * @type String
	 * @author QuangPham
	 * @since 2013/08/23
	 */
	public static String formatNumber(int numberFormat, String patent) {

		String strNumber = null;
		try {
			int convertUserId = Integer.valueOf(numberFormat);
			DecimalFormat decimalFormat = new DecimalFormat(patent);
			strNumber = String.valueOf(decimalFormat.format(convertUserId));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return strNumber;
	}
	
	public static void copyfile(String srFile, String dtFile){
		  try{
		  File f1 = new File(srFile);
		  File f2 = new File(dtFile);
		  InputStream in = new FileInputStream(f1);
		  
		  //For Append the file.
		//  OutputStream out = new FileOutputStream(f2,true);

		  //For Overwrite the file.
		  OutputStream out = new FileOutputStream(f2);

		  byte[] buf = new byte[1024];
		  int len;
		  while ((len = in.read(buf)) > 0){
		  out.write(buf, 0, len);
		  }
		  in.close();
		  out.close();
		  System.out.println("File copied.");
		  }
		  catch(FileNotFoundException ex){
		  System.out.println(ex.getMessage() + " in the specified directory.");
		  System.exit(0);
		  }
		  catch(IOException e){
		  System.out.println(e.getMessage());  
		  }
		  }
	
	public static Member checkEmailExist(String email) {
		// Create model systemUser
		Member member = new Member();
		MemberDAO memberDAO = new MemberDAOImpl();
		try {
			member = memberDAO.checkEmailExists(email);
			if (member == null) {
				// Set Error Message : [User is not exist.]
			}
		} catch (Exception e) {
			// Save log file txt
			// Print error mgs
			e.printStackTrace();
		}
		return member;
	}
	
	/**
	   * Gets value from object using reflection.
	   * 
	   * @param object the object
	   * @param fieldName the field
	   * @return the value
	   */
	public static String getValueFromObject(Object object, String fieldName) {
	 
	    // get class
	    Class clazz = object != null ? object.getClass() : null;
	    if (clazz == null) {
	      return null;
	    }
	 
	    // get object value using reflection
	    String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
	    try {
	      @SuppressWarnings("unchecked")
	      Method method = clazz.getMethod(getterName);
	      Object valueObject = method.invoke(object, (Object[]) null);
	      return valueObject != null ? valueObject.toString() : "";
	    } catch (Exception e) {
	      // ignore all reflection errors
	    }
	 
	    return null;
	  }


}
